package com.sunwayhorizo.health.business.clinic.orders.basedef;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.ejb.Stateless;

import org.jboss.seam.Component;
import org.jboss.seam.annotations.Name;

import com.sunwayhorizo.health.business.base.BaseManager;
import com.sunwayhorizo.health.business.clinic.orders.query.OrdersQueryLocal;
import com.sunwayhorizo.health.business.dto.DictionaryDTO;
import com.sunwayhorizo.health.business.dto.EntityNameDTO;
import com.sunwayhorizo.health.business.dto.PageDTO;
import com.sunwayhorizo.health.business.dto.ResultsDTO;
import com.sunwayhorizo.health.business.dto.clinic.orders.SubstanceAdmtDTO;
import com.sunwayhorizo.health.business.dto.econ.InvoiceElementDTO;
import com.sunwayhorizo.health.business.dto.pham.ManufacturedMaterialDTO;
import com.sunwayhorizo.health.common.DataTypeUtil;
import com.sunwayhorizo.health.common.ListUtil;
import com.sunwayhorizo.health.common.StrUtil;
import com.sunwayhorizo.health.ets.base.service.ETSService;
import com.sunwayhorizo.health.ets.exceptions.ETSBadParameterException;
import com.sunwayhorizo.health.ets.exceptions.ETSDataException;
import com.sunwayhorizo.health.hl7.common.Hl7Exception;
import com.sunwayhorizo.health.hl7.datatypes.BAG_EN;
import com.sunwayhorizo.health.hl7.datatypes.CE;
import com.sunwayhorizo.health.hl7.datatypes.II;
import com.sunwayhorizo.health.hl7.datatypes.PQ;
import com.sunwayhorizo.health.hl7.datatypes.common.CSImpl;
import com.sunwayhorizo.health.hl7.datatypes.common.ENImpl;
import com.sunwayhorizo.health.hl7.datatypes.common.PQImpl;
import com.sunwayhorizo.health.hl7.persistent.RimCoreEntyNames;
import com.sunwayhorizo.health.hl7.rim.Act;
import com.sunwayhorizo.health.hl7.rim.ActParticipation;
import com.sunwayhorizo.health.hl7.rim.ActRelationship;
import com.sunwayhorizo.health.hl7.rim.ControlAct;
import com.sunwayhorizo.health.hl7.rim.InvoiceElement;
import com.sunwayhorizo.health.hl7.rim.ManufacturedMaterial;
import com.sunwayhorizo.health.hl7.rim.Role;
import com.sunwayhorizo.health.hl7.rim.SubstanceAdministration;
import com.sunwayhorizo.health.hl7.vocabulary.ActClass;
import com.sunwayhorizo.health.hl7.vocabulary.ActCode;
import com.sunwayhorizo.health.hl7.vocabulary.ActMood;
import com.sunwayhorizo.health.hl7.vocabulary.ActRelationshipType;
import com.sunwayhorizo.health.hl7.vocabulary.Direction;
import com.sunwayhorizo.health.hl7.vocabulary.EntityCode;
import com.sunwayhorizo.health.hl7.vocabulary.EntityDeterminer;
import com.sunwayhorizo.health.hl7.vocabulary.EntityIICode;
import com.sunwayhorizo.health.hl7.vocabulary.EntityNamePartType;
import com.sunwayhorizo.health.hl7.vocabulary.EntityNameUse;
import com.sunwayhorizo.health.hl7.vocabulary.ParticipationType;
import com.sunwayhorizo.health.hl7.vocabulary.RoleClass;
import com.sunwayhorizo.health.hl7.vocabulary.RoleCode;

/**
 * @ClassName SubstanceAdmtDefManager <br>
 * @PackageName com.sunwayhorizo.health.business.clinic.orders.basedef <br>
 * @Description 药疗医嘱项目定义session bean <br>
 * @Author jinzw <br>
 * @Date 2010-03-07 <br>
 * @Version 1.0 <br>
 * @ModifiedDesc <br>
 * @ModifiedDate <br>
 * @ModifiedBy <br>
 * @Copyright 2010-2020 北京三维海容 All Rights Reserved. <br>
 */

@Name("SubstanceAdmtDefManager")
@Stateless
public class SubstanceAdmtDefManager extends BaseManager implements SubstanceAdmtDefManagerLocal
{

    private InvoiceElementDefManagerLocal inveElementDefManager = (InvoiceElementDefManagerLocal) Component.getInstance("InvoiceElementDefManager");
    private OrdersQueryLocal ordersQuery = (OrdersQueryLocal) Component.getInstance("OrdersQuery");
    private  ETSService eTSService = (ETSService) Component.getInstance("ETSService");
    
    @Override
    public ResultsDTO newSubstanceAdmtDefManager(SubstanceAdmtDTO substanceAdmtDTO) throws Hl7Exception
    {
        if(substanceAdmtDTO == null || substanceAdmtDTO.getmMaterial() == null || StrUtil.isEmpty(substanceAdmtDTO.getmMaterial().getMaterialclass()))
        {
            log.info("药理目录编码为空,不能保存");
            return this.getResultsDTO("药理目录编码为空,不能保存", true, null);
        }
        //创建药物定义动作
        SubstanceAdministration subAdmt = this.getActFactory().newSubstanceAdministration(ActMood.DEF, ActCode.DRUG, null);
        
        //给药物定义动作赋值
        subAdmt = converSubstanceAdmt(subAdmt,substanceAdmtDTO);
        
        //创建药品基本信息角色
        Role drugInfoRole = constructionDrugInfoRole(substanceAdmtDTO);
        ActParticipation part = getActFactory().newActParticipation();
        part.setTypeCode("SBJ");
        addParticipation(drugInfoRole, part);
        
        //创建药品基本信息动作与药品费用明细动作关联
        if(ListUtil.isNotEmpty(substanceAdmtDTO.getInvoiceElementList()))
        {
            for(InvoiceElementDTO invoiceElement : substanceAdmtDTO.getInvoiceElementList())
            {
                InvoiceElement inve = inveElementDefManager.newInvoiceElementDet(invoiceElement);
                if(inve != null)
                {
                    ActRelationship relation = getActFactory().newActRelationship();
                    relation.setTypeCode(ActRelationshipType.CHRG);
                    addRelationship(inve, relation, Direction.TARGET);
                }
            }
        }
      
        //创建ContorAct关系
        ControlAct controlAct = newControlAct(subAdmt);
        
        save(controlAct);
        
        log.info("保存成功 actid="+subAdmt.getActId());
        
        return this.getResultsDTO("药品基本信息保存成功", true, subAdmt.getActId());
    }
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public ResultsDTO delSubstanceAdmtDefManager(List ids) throws Hl7Exception
    {
        
        if (ListUtil.isEmpty(ids))
        {
            log.info("删除药品基本信息失败，数据为空");
            return getResultsDTO("删除药品基本信息失败，数据为空", false, null);
        }
        for(int i=0; i<ids.size(); i++)
        {
            String id = (String)ids.get(i);
            Act act = baseQuery.findActByActId(Long.valueOf(id));
            List<InvoiceElement> inveList = (List<InvoiceElement>)act.getSourceActListByTargetAct(ActClass.INVE, ActCode.DRUG);
            int j= delete(act,ParticipationType.SBJ);
            if(j == 0)
            {
                log.info("药品基本信息删除失败");
            }
            int k = batchDelete(inveList,ParticipationType.IND);
            if(k == 0)
            {
                log.info("药品费用信息删除失败");
            }
        }
      
        return getResultsDTO("删除药品基本信息成功", true, null);
    }
    
    
    @SuppressWarnings({ "null", "unchecked" })
    @Override
    public ResultsDTO updSubstanceAdmtDefManager(SubstanceAdmtDTO substanceAdmtDTO) throws Hl7Exception
    {
        if(substanceAdmtDTO == null && StrUtil.isEmpty(substanceAdmtDTO.getActId()))
        {
            log.info("药品基本信息为空,不能进行修改");
            return this.getResultsDTO("药品基本信息为空，不能修改", false, null);
        }
        
        //得到药品基本信息动作
        SubstanceAdministration subAdmt = (SubstanceAdministration)baseQuery.findActByActId(Long.valueOf(substanceAdmtDTO.getActId()));
        
        //修改药品动作信息
        subAdmt = converSubstanceAdmt(subAdmt,substanceAdmtDTO);
        
        //修改药品费用信息
        List<InvoiceElement> inveList = (List<InvoiceElement>)subAdmt.getSourceActListByTargetAct(ActClass.INVE, ActCode.DRUG);
        batchDelete(inveList,ParticipationType.IND);
        //创建药品基本信息动作与药品费用明细动作关联
        if(ListUtil.isNotEmpty(substanceAdmtDTO.getInvoiceElementList()))
        {
            for(InvoiceElementDTO invoiceElement : substanceAdmtDTO.getInvoiceElementList())
            {
                InvoiceElement inve = inveElementDefManager.newInvoiceElementDet(invoiceElement);
                if(inve != null)
                {
                    subAdmt.addIBActRelationship(ActRelationshipType.CHRG, inve);
                }
            }
        }
        
        //修改药品实体信息
        ManufacturedMaterial mmat = (ManufacturedMaterial)subAdmt.getHl7EntityByAct(ParticipationType.SBJ, RoleCode.DRUG);
            List<RimCoreEntyNames> names = mmat.getEntyNamesList();
            if(ListUtil.isNotEmpty(names))
            {
                for(int i=0 ; i<names.size() ; i++)
                {
                    RimCoreEntyNames name = names.get(i);
                    names.remove(name);
                    em.remove(name);
                }
            }
        mmat =  converMaterialToMaterialDTO(mmat,substanceAdmtDTO.getmMaterial());
       
        em.merge(mmat);
        log.info("修改药品实体信息成功"+mmat.getEntityId());
       
       update(subAdmt);
       log.info("修改药品动作信息成功"+subAdmt.getActId());
       
        return this.getResultsDTO("药品基本信息修改成功", true, subAdmt.getActId().toString());
    }
    
    public ResultsDTO findSubstanceAdmtDefList(String materialclass,PageDTO pageDTO) throws Hl7Exception
    {
       //根据materialclassCode拿到所有的子节点code
        List<String> materialclassCodes = eTSService.findLeafDirCode("pharmacologyClassB", "", "", materialclass);
        
       if(ListUtil.isEmpty(materialclassCodes))
       {
           materialclassCodes = new ArrayList<String>();
           materialclassCodes.add(materialclass);
       }
       List<SubstanceAdministration> subAdmes = ordersQuery.findSubstanceAdministrationByCond(materialclassCodes, pageDTO.getPageNo(), pageDTO.getPageSize());
      
       List<SubstanceAdmtDTO> subAdmtDTOList = new ArrayList<SubstanceAdmtDTO>();
       
       if(ListUtil.isNotEmpty(subAdmes))
       {
           for(SubstanceAdministration subAdmt : subAdmes)
           {
               SubstanceAdmtDTO substanceAdmtDTO = new SubstanceAdmtDTO();
               substanceAdmtDTO =  converSubAdmtDTOFormSubAdmt(subAdmt,substanceAdmtDTO);
               subAdmtDTOList.add(substanceAdmtDTO);
           }
           pageDTO.setTotalRecord((int)ordersQuery.findSubstanceAdministrationByCond(materialclassCodes));
           return getResultsDTO("药品查询成功", true, subAdmtDTOList, pageDTO);
       }
      
       return this.getResultsDTO("没有找到相关药品信息", true, null);
    }
    
    @SuppressWarnings("unused")
    public ResultsDTO validationSubAdmtId(String id,String entyId) throws Hl7Exception
    {
        boolean flag = baseQuery.validateEntyIIExsit(id, EntityIICode.DRUGCODE.toString(),entyId);
        if(true)
        {
            return this.getResultsDTO("该药品编码已经存在", true, "0");
        }
        else
            return this.getResultsDTO("该药品编码不存在", true, "1");
    }
    
    
    private SubstanceAdmtDTO converSubAdmtDTOFormSubAdmt(SubstanceAdministration subAdmt,SubstanceAdmtDTO subAdmtDto) throws Hl7Exception
    {
        subAdmtDto.setActId(subAdmt.getActId()+"");
        //用药途径
        subAdmtDto.setRouteCode(this.getDictionaryFactory().getDictionaryDTOByCe(subAdmt.getRouteCode()));
        //频次
        if(subAdmt.getRepeatNumber() != null && subAdmt.getRepeatNumber().low() != null)
        {
            subAdmtDto.setRepeatNumber(subAdmt.getRepeatNumber().low().literal().toString());
        }
        if(subAdmt.getFreqInterval() != null && subAdmt.getFreqInterval().value() != null)
        {
            //频次间隔
            subAdmtDto.setFreqIntervalValue(subAdmt.getFreqInterval().value().literal().stringValue());
            //频次单位
            subAdmtDto.setFreqIntervalUnit(subAdmt.getFreqInterval().unit().code().stringValue());
        }
       
        if(subAdmt.getDoseQuantity() != null && subAdmt.getDoseQuantity() != null)
        {
            //每次用量
            subAdmtDto.setDoseQuantity(subAdmt.getDoseQuantity().low().value().literal().stringValue());
            //每次单位
            subAdmtDto.setDoseUnit(subAdmt.getDoseQuantity().low().unit().code().stringValue());
        }
       
        if(subAdmt.getSaMaxdoseValue() != null && subAdmt.getSaMaxdoseValue().value() != null)
        {
            //最大用量
            subAdmtDto.setMaxDoseQuantity(subAdmt.getSaMaxdoseValue().value().literal().toString());
            //最大用量单位
            subAdmtDto.setMaxDoseUnit((subAdmt.getSaMaxdoseValue().unit().code().toString().equals("<Null:NullFlavor: NI>") ? "" : subAdmt.getSaMaxdoseValue().unit().code().toString()));
        }
        if(subAdmt.getSaMaxdaysValue() != null && subAdmt.getSaMaxdaysValue().value() != null)
        {
            //最长天数
            subAdmtDto.setMaxUsedDays(subAdmt.getSaMaxdaysValue().value().literal().stringValue());
        }
        
        //药品费用信息集合
        subAdmtDto.setInvoiceElementList(converInveElementDTOListFormInves(subAdmt));
        
        //药品基本信息
        subAdmtDto.setmMaterial(converMMaterialDTOFormSubAdmt(subAdmt));
      
        return subAdmtDto;
    }
    
    
    //构建药物医嘱定义动作信息
    private SubstanceAdministration converSubstanceAdmt(SubstanceAdministration subAdmt,SubstanceAdmtDTO substanceAdmtDTO) throws Hl7Exception
    {
        //药理分类
        subAdmt.setLevelCode(DataTypeUtil.getCE(substanceAdmtDTO.getmMaterial().getMaterialclass()));
        //用药途径
        CE routeCode = getDictionaryFactory().getCeByDictionaryDTO(substanceAdmtDTO.getRouteCode());
        subAdmt.setRouteCode(routeCode);
        
        //频次
        subAdmt.setRepeatNumber(DataTypeUtil.getIVL_INT(Long.valueOf((StrUtil.isEmpty(substanceAdmtDTO.getRepeatNumber()) ? "1" : substanceAdmtDTO.getRepeatNumber()))));
        
        //频次间隔-单位
        PQ freqInterval = DataTypeUtil.getPQ((StrUtil.isNotEmpty(substanceAdmtDTO.getFreqIntervalValue()) ? substanceAdmtDTO.getFreqIntervalValue() : "1"), (StrUtil.isNotEmpty(substanceAdmtDTO.getFreqIntervalUnit()) ? substanceAdmtDTO.getFreqIntervalUnit() : ""));
        subAdmt.setFreqInterval(freqInterval);
        
        //每次用量-单位
        subAdmt.setDoseQuantity(DataTypeUtil.getIVL_PQ((StrUtil.isEmpty(substanceAdmtDTO.getDoseQuantity()) ? "" : substanceAdmtDTO.getDoseQuantity()),(StrUtil.isEmpty(substanceAdmtDTO.getDoseUnit()) ? "" : substanceAdmtDTO.getDoseUnit())));
        
        //最大用量-单位
        subAdmt.setSaMaxdoseValue(DataTypeUtil.getPQ((StrUtil.isEmpty(substanceAdmtDTO.getMaxDoseQuantity()) ? "" : substanceAdmtDTO.getMaxDoseQuantity()), StrUtil.isEmpty(substanceAdmtDTO.getMaxDoseUnit()) ? "" : substanceAdmtDTO.getMaxDoseUnit()));
        
        //最长天数
        subAdmt.setSaMaxdaysValue(DataTypeUtil.getPQ((StrUtil.isEmpty(substanceAdmtDTO.getMaxUsedDays()) ? "" : substanceAdmtDTO.getMaxUsedDays()),""));
        
        return subAdmt;
    }

    //构建药品基本信息角色
    private Role constructionDrugInfoRole(SubstanceAdmtDTO substanceAdmtDTO) throws Hl7Exception
    {
        if(substanceAdmtDTO == null || substanceAdmtDTO.getmMaterial()==null)
        {
            log.info("药品基本信息为空，不能创建药品角色");
            return null;
        }
        
        //创建药品实体信息
        ManufacturedMaterial mMeterial = this.getEntityFactory().newManufacturedMaterial(DataTypeUtil.getCE(EntityCode.DRUG.code().toString()), EntityDeterminer.KIND, null);
        
        //给药品实体信息赋值
        mMeterial =  converMaterialToMaterialDTO(mMeterial,substanceAdmtDTO.getmMaterial());
        
        //创建药品基本信息角色
        Role role = this.getRoleFactory().newRole(RoleClass.IDENT, DataTypeUtil.getCE(RoleCode.DRUG.code().toString()), mMeterial, mMeterial);
        
        return role;
    }
    
    //组装药品基本信息dto
    private ManufacturedMaterialDTO converMMaterialDTOFormSubAdmt(SubstanceAdministration subAdmt) throws Hl7Exception
    {
        ManufacturedMaterial mmat = (ManufacturedMaterial)subAdmt.getHl7EntityByAct(ParticipationType.SBJ,RoleCode.DRUG);
        if(mmat == null) return null;
        
        ManufacturedMaterialDTO manuMaterialDTO = new ManufacturedMaterialDTO();
        
        manuMaterialDTO.setEntyId(mmat.getEntityId()+"");
        
        //药品编码
        II id = mmat.getId(EntityIICode.DRUGCODE);
        manuMaterialDTO.setId((id == null ? "" : id.extension().toString()));
        
        //药理分类
        manuMaterialDTO.setMaterialclass((subAdmt.getLevelCode() != null ? subAdmt.getLevelCode().code().toString() : ""));
        
        //药品名称
        List<EntityNameDTO> nameList = converEntyNameFormMeterialName(mmat);
        if(ListUtil.isNotEmpty(nameList))
        {
            manuMaterialDTO.setEntityNames(nameList);
            //列表显示名称
            for(EntityNameDTO entityNameDTO : nameList)
            {
                if(entityNameDTO.getNameFlag() != null && entityNameDTO.getNameFlag().equals("C"))
                {
                    manuMaterialDTO.setEntityName(entityNameDTO); 
                }
            }
        }
        
        
        //药品标识
        manuMaterialDTO.setIndicator(getDictionaryFactory().getDictionaryDTOByCe(mmat.getIndicatorCode()));
        //剂型
        manuMaterialDTO.setForm(getDictionaryFactory().getDictionaryDTOByCe(mmat.getFormCode()));
        if(mmat.getQuantity() != null && mmat.getQuantity().isEmpty().isFalse())
        {
            PQImpl pq = (PQImpl) mmat.getQuantity().toSet().iterator().next();
            //剂量
            manuMaterialDTO.setQuautity(pq.value().literal().toString());
            //剂量单位
            manuMaterialDTO.setUnit(pq.unit().code().toString());
        }
        if(mmat.getConcentration() != null && mmat.getConcentration().isNull().isFalse())
        {
            //浓度
            manuMaterialDTO.setConcentration(mmat.getConcentration().value().literal().toString());
            //浓度单位
            manuMaterialDTO.setConcentrationUnit(mmat.getConcentration().unit().code().toString());
        }
        if(mmat.getVolume() != null && mmat.getVolume().isNull().isFalse())
        {
            //体积
            manuMaterialDTO.setVolume(mmat.getVolume().value().literal().toString());
            //体积单位
            manuMaterialDTO.setVolumeUnit(mmat.getVolume().unit().code().toString());
        }
        if(mmat.getWeigh() != null && mmat.getWeigh().isNull().isFalse())
        {
            //重量
            manuMaterialDTO.setWeigh(mmat.getWeigh().value().literal().toString());
            //重量单位
            manuMaterialDTO.setWeighUnit(mmat.getWeigh().unit().code().toString());
        }
        //规格
        manuMaterialDTO.setSpec((mmat.getLotNumberText() != null ? mmat.getLotNumberText().toString() : ""));
        
        //毒麻分类
        manuMaterialDTO.setRiskCode(getDictionaryFactory().getDictionaryDTOByCe(mmat.getRiskCode()));
        //限制级别
        manuMaterialDTO.setLimitedLevel(getDictionaryFactory().getDictionaryDTOByCe(mmat.getMtLimitedLevel()));
        //医保分类
        manuMaterialDTO.setInsuranceClass(getDictionaryFactory().getDictionaryDTOByCe(mmat.getInsuranceClassCode()));
        //医保编码
        manuMaterialDTO.setInsuranceCode((mmat.getIndicatorCode() != null ? mmat.getIndicatorCode().code().stringValue() : ""));
        //是否处方药标志
        manuMaterialDTO.setOtcInd(mmat.getOtcFlag().toString());
        //是否需要皮试
        manuMaterialDTO.setSkinTestInd(mmat.getSkintestFlag().toString());
        //违禁标志
        manuMaterialDTO.setContrabandInd(mmat.getContrabandFlag().toString());
     
        return manuMaterialDTO;
    }
    
    //构建药品基本信息实体信息
    private ManufacturedMaterial converMaterialToMaterialDTO(ManufacturedMaterial mMeterial,ManufacturedMaterialDTO mMaterialDTO) throws Hl7Exception
    {
        if(mMaterialDTO == null) return null;
        
        //药品编码
        if(StrUtil.isNotEmpty(mMaterialDTO.getId()))
        {
            II id = DataTypeUtil.getII(root, mMaterialDTO.getId(), EntityIICode.DRUGCODE.toString());
            mMeterial.setId(id);
        }
        
        //药品名称
        if(ListUtil.isNotEmpty(mMaterialDTO.getEntityNames()))
        {
            converMeterialNameFormEntyName(mMeterial,mMaterialDTO.getEntityNames());
        }
        //药品标识
        mMeterial.setIndicatorCode(getDictionaryFactory().getCeByDictionaryDTO(mMaterialDTO.getIndicator()));
        
        //剂型
        mMeterial.setFormCode(getDictionaryFactory().getCeByDictionaryDTO(mMaterialDTO.getForm()));
        //剂量-单位
        mMeterial.setQuantity(DataTypeUtil.getSET_PQ((StrUtil.isEmpty(mMaterialDTO.getQuautity()) ? "" : mMaterialDTO.getQuautity()), (StrUtil.isEmpty(mMaterialDTO.getUnit()) ? "" : mMaterialDTO.getUnit())));
        //浓度-浓度单位
        mMeterial.setConcentration(DataTypeUtil.getPQ((StrUtil.isEmpty(mMaterialDTO.getConcentration()) ? "" : mMaterialDTO.getConcentration()), (StrUtil.isEmpty(mMaterialDTO.getConcentrationUnit()) ? "" : mMaterialDTO.getConcentrationUnit())));
        //体积-体积单位
        mMeterial.setVolume(DataTypeUtil.getPQ((StrUtil.isEmpty(mMaterialDTO.getVolume()) ? "" : mMaterialDTO.getVolume()), (StrUtil.isEmpty(mMaterialDTO.getVolumeUnit()) ? "" : mMaterialDTO.getVolumeUnit())));
        //重量-重量单位
        mMeterial.setWeigh(DataTypeUtil.getPQ((StrUtil.isEmpty(mMaterialDTO.getWeigh()) ? "" : mMaterialDTO.getWeigh()), StrUtil.isEmpty(mMaterialDTO.getWeighUnit()) ? "" : mMaterialDTO.getWeighUnit()));
        //规格
        mMeterial.setLotNumberText(DataTypeUtil.getST(mMaterialDTO.getSpec()));
        
        //毒麻分类
        mMeterial.setRiskCode(getDictionaryFactory().getCeByDictionaryDTO(mMaterialDTO.getRiskCode()));
        //限制级别
        mMeterial.setMtLimitedLevel(getDictionaryFactory().getCeByDictionaryDTO(mMaterialDTO.getLimitedLevel()));
        //医保分类
        mMeterial.setInsuranceClassCode(getDictionaryFactory().getCeByDictionaryDTO(mMaterialDTO.getInsuranceClass()));
        //医保编码
        mMeterial.setInsuranceCode(DataTypeUtil.getST(mMaterialDTO.getInsuranceCode()));
        //是否处方药标志
        mMeterial.setOtcFlag(DataTypeUtil.getST(mMaterialDTO.getOtcInd()));
        //是否需要皮试
        mMeterial.setSkintestFlag(DataTypeUtil.getST(mMaterialDTO.getSkinTestInd()));
        //违禁标志
        mMeterial.setContrabandFlag(DataTypeUtil.getST(mMaterialDTO.getContrabandInd()));
        
        return mMeterial;
    }
    
    //组装药品费用信息dto集合
    @SuppressWarnings("unchecked")
    private List<InvoiceElementDTO> converInveElementDTOListFormInves(SubstanceAdministration subAdmt) throws Hl7Exception
    {
        List<InvoiceElementDTO> inveDtolist = new ArrayList<InvoiceElementDTO>();
        List<InvoiceElement> inves = (List<InvoiceElement>)subAdmt.getSourceActListByTargetAct(ActClass.INVE,ActCode.DRUG);
        if(ListUtil.isNotEmpty(inves))
        {
            for(InvoiceElement inve : inves)
            {
                InvoiceElementDTO inveDto = inveElementDefManager.converInvoiceElementDTOFormInve(inve);
                inveDtolist.add(inveDto);
            }
        }
        return inveDtolist;
    }
    
    private void converMeterialNameFormEntyName(ManufacturedMaterial mMeterial,List<EntityNameDTO> entityNames) throws Hl7Exception
    {
        if(ListUtil.isEmpty(entityNames)) return;
        
        for(EntityNameDTO entityNameDTO : entityNames)
        {
            // 名称
            if (!StrUtil.isEmpty(entityNameDTO.getCurrencyName()))
            {
                String[] name = { entityNameDTO.getCurrencyName() };
                String[] type = { EntityNamePartType.CHINAES_NAME.code().toString() };
                String nameUseCode = (StrUtil.isEmpty(entityNameDTO.getNameFlag()) ? EntityNameUse.C.code().toString() : entityNameDTO.getNameFlag());
                BAG_EN bagName = DataTypeUtil.getBagEN(name, type, nameUseCode);
                mMeterial.setName(bagName);
            }

            // 简码
            if (!StrUtil.isEmpty(entityNameDTO.getPinyinCode()))
            {
                String[] name = { entityNameDTO.getPinyinCode() };
                String[] type = { EntityNamePartType.SEARCH.code().toString() };
                String useCode = EntityNameUse.SRCH.code().toString();
                BAG_EN bagPing = DataTypeUtil.getBagEN(name, type, useCode);
                mMeterial.setName(bagPing);
            }
            // 五笔码
            if (!StrUtil.isEmpty(entityNameDTO.getWubiCode()))
            {
                String[] name = { entityNameDTO.getWubiCode() };
                String[] type = { EntityNamePartType.SOUNDEX.code().toString() };
                String useCode = EntityNameUse.SNDX.code().toString();
                BAG_EN bagPing = DataTypeUtil.getBagEN(name, type, useCode);
                mMeterial.setName(bagPing);
            }
            // 全拼
            if (!StrUtil.isEmpty(entityNameDTO.getFullSpellCode()))
            {
                String[] ping = { entityNameDTO.getFullSpellCode() };
                String[] pingType = { EntityNamePartType.PHON.code().toString() };
                String pingUseCode = EntityNameUse.PHON.code().toString();
                BAG_EN bagPing = DataTypeUtil.getBagEN(ping, pingType, pingUseCode);
                mMeterial.setName(bagPing);
            }
        }
    }
    
    @SuppressWarnings("rawtypes")
    private List<EntityNameDTO> converEntyNameFormMeterialName(ManufacturedMaterial mMeterial) throws Hl7Exception
    {
        BAG_EN names = mMeterial.getName();
        if (names != null)
        {
            List<DictionaryDTO>  nameUeseCodesList = eTSService.findDictionaryDtosListByCond("DrugAlias",null,null,null);
            List mList = names.toList();
            List<EntityNameDTO> entityNameDTOList = new ArrayList<EntityNameDTO>();
            if (ListUtil.isNotEmpty(mList))
            {
                EntityNameDTO  entityNameDTO = null;
                for (int i = 0; i < mList.size(); i++)
                {
                    entityNameDTO = new EntityNameDTO();
                    ENImpl en = (ENImpl) mList.get(i);
                    Set set = (Set) en.use().toSet();
                    String code = "";
                    if (!set.isEmpty())
                    {
                        CSImpl use = (CSImpl) set.iterator().next();
                        code = use.code().toString();
                    }
                    
                    if(ListUtil.isNotEmpty(nameUeseCodesList))
                    {
                        for(DictionaryDTO dictionaryDTO : nameUeseCodesList)
                        {
                            if (code.equals(dictionaryDTO.getConceptCode()))
                            {
                                entityNameDTO.setCurrencyName(en.formatted().toString());
                                entityNameDTO.setNameFlag(dictionaryDTO.getConceptCode());
                                break;
                            }
                        }
                    }
                   
                    if (code.equals(EntityNameUse.PHON.code().toString()))
                    {
                        entityNameDTO.setFullSpellCode(en.formatted().toString());
                    }
                    if (code.equals(EntityNameUse.SRCH.code().toString()))
                    {
                        entityNameDTO.setPinyinCode(en.formatted().toString());
                    }
                    if (code.equals(EntityNameUse.SNDX.code().toString()))
                    {
                        entityNameDTO.setWubiCode(en.formatted().toString());
                    }
                    entityNameDTOList.add(entityNameDTO);
                }
            }
            log.info("组装好的药品名称DTO数目="+entityNameDTOList.size());
            return entityNameDTOList;
        }
        return null;
    }
    

}
